package com.warom.sdg.websocket.handler;

import android.content.Context;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.warom.sdg.config.PlcMeasurementUtils;
import com.warom.sdg.websocket.WebSocketClient;
import com.warom.sdg.websocket.WebSocketConfig;
import com.warom.sdg.websocket.WebSocketMessage;
import com.warom.sdg.util.LogUtils;
import com.warom.sdg.service.PlcDataService;
import com.warom.sdg.config.PlcMeasurementConfig;
import com.warom.sdg.config.MeasurementPoint;
import com.warom.sdg.model.DeviceType;
import com.warom.sdg.model.PlcDeviceEntity;
import com.warom.sdg.websocket.dto.WebSocketMessageResponse;
import com.warom.sdg.webview.jsinterface.WebViewJsVentilationInterface;

import java.util.ArrayList;
import java.util.List;

/**
 * 命令消息处理器
 * 负责处理WebSocket接收到的命令类型消息
 */
public class CommandHandler {
    private static final String TAG = "CommandHandler";
    private static final Gson gson = new Gson();

    private final Context context;
    private final WebSocketClient webSocketClient;
    private final CommandCallback callback;
    private WebViewJsVentilationInterface ventilationInterface;

    /**
     * 命令回调接口
     * 用于需要Service参与的操作
     */
    public interface CommandCallback {
        void reconnect();

        void startHeartbeat();

        void sendMessage(String message);

        PlcDataService getPlcDataService();
    }

    /**
     * 构造函数
     * 
     * @param context         上下文
     * @param webSocketClient WebSocket客户端
     * @param callback        命令回调
     */
    public CommandHandler(Context context, WebSocketClient webSocketClient, CommandCallback callback) {
        this.context = context;
        this.webSocketClient = webSocketClient;
        this.callback = callback;

        // 初始化通风控制接口
        this.ventilationInterface = new WebViewJsVentilationInterface(context);
    }

    /**
     * 处理WebSocketMessage对象形式的命令
     * 
     * @param message WebSocketMessage对象
     */
    public void handleCommand(WebSocketMessage message) {
        if (message == null || message.getCommand() == null) {
            Log.e(TAG, "无效的命令消息");
            return;
        }

        String command = message.getCommand();
        Log.d(TAG, "处理WebSocketMessage命令: " + command);

        // 记录日志
        LogUtils.logOperation("WebSocket", "命令", "收到命令: " + command);

        switch (command) {
            case "controlSingle":
                // 单设备控制命令
                handleControlSingleCommand(message);
                break;
            default:
                Log.d(TAG, "未知命令: " + command);
                break;
        }
    }

    /**
     * 处理重连命令
     */
    private void handleReconnect() {
        if (callback != null) {
            callback.reconnect();
        }
    }

    /**
     * 处理更新配置命令
     * 
     * @param data 配置数据
     */
    private void handleUpdateConfig(JsonObject data) {
        WebSocketConfig config = WebSocketConfig.getInstance(context);

        try {
            boolean needRestart = false;

            // 更新WebSocket URL
            if (data.has("ws_url")) {
                String wsUrl = data.get("ws_url").getAsString();
                config.setWebSocketUrl(wsUrl);
                needRestart = true;
            }

            // 更新心跳间隔
            if (data.has("heartbeat_interval")) {
                int interval = data.get("heartbeat_interval").getAsInt();
                config.setHeartbeatInterval(interval);

                // 重启心跳任务
                if (callback != null) {
                    callback.startHeartbeat();
                }
            }

            // 更新自动重连设置
            if (data.has("auto_reconnect")) {
                boolean autoReconnect = data.get("auto_reconnect").getAsBoolean();
                config.setAutoReconnect(autoReconnect);
            }

            // 更新最大重连尝试次数
            if (data.has("max_reconnect_attempts")) {
                int attempts = data.get("max_reconnect_attempts").getAsInt();
                config.setMaxReconnectAttempts(attempts);
            }

            Log.d(TAG, "WebSocket配置已更新");

            // 如果需要重启连接
            if (needRestart && callback != null) {
                callback.reconnect();
            }

        } catch (Exception e) {
            Log.e(TAG, "更新配置异常: " + e.getMessage(), e);
        }
    }



    /**
     * 处理单设备控制命令 (WebSocketMessage格式)
     * 
     * @param message 控制消息
     */
    private void handleControlSingleCommand(WebSocketMessage message) {
        // 使用WebSocketMessageResponse作为返回体
        WebSocketMessageResponse messageResponse = new WebSocketMessageResponse();
        Log.d(TAG, "处理单设备控制命令(WebSocketMessage): " + message.toJson());
        try {
            // 确保PLC数据服务已设置
            if (callback != null && callback.getPlcDataService() != null) {
                // 设置PLC数据服务到通风控制接口
                ventilationInterface.setPlcDataService(callback.getPlcDataService());

                // 从消息中提取设备英文名和控制值
                String englishName = message.getEnglishName();
                if (englishName != null && !englishName.isEmpty()) {
                    // 获取控制值
                    String content = message.getContent();
                    // 确定操作类型
                    String action = "1".equals(content) ? "on" : "off";

                    // 查找对应的测点及其设备类型
                    PlcMeasurementUtils.MeasurementPointInfo pointInfo = PlcMeasurementUtils
                            .findMeasurementPointInfoByEnglishName(englishName);
                    if (pointInfo == null) {
                        throw new IllegalArgumentException("未找到设备: " + englishName);
                    }

                    MeasurementPoint point = pointInfo.getPoint();
                    DeviceType deviceType = pointInfo.getDeviceType();

                    Log.d(TAG, "找到测点: " + point.getName() + ", 地址: " + point.getAddress() + ", 设备类型: "
                            + deviceType.getDisplayName());

                    // 创建测点列表
                    List<MeasurementPoint> points = new ArrayList<>();
                    points.add(point);

                    // 获取设备ID
                    String deviceId = "1"; // 默认设备ID

                    // 尝试获取该设备类型的设备ID
                    int deviceTypeId = deviceType.getId();
                    List<PlcDeviceEntity> deviceList = ventilationInterface.getDeviceRepository()
                            .listByDeviceTypeId(deviceTypeId);
                    if (deviceList != null && !deviceList.isEmpty()) {
                        deviceId = String.valueOf(deviceList.get(0).getDeviceId());
                        Log.d(TAG, "找到设备ID: " + deviceId + " 对应设备类型: " + deviceType.getDisplayName());
                    } else {
                        Log.w(TAG, "未找到设备类型" + deviceType.getDisplayName() + "的设备，使用默认设备ID: " + deviceId);
                    }

                    // 直接调用controlDevices方法进行控制
                    boolean success = ventilationInterface.controlDevices(points, deviceId, action);

                    if (success) {
                        messageResponse = new WebSocketMessageResponse(true, "设备控制成功");
                    } else {
                        messageResponse = new WebSocketMessageResponse(false, "设备控制失败");
                    }
                    Log.d(TAG, "单设备控制命令已处理，结果: " + (success ? "成功" : "失败"));
                } else {
                    messageResponse = new WebSocketMessageResponse(true, "设备控制成功");
                }
            } else {
                messageResponse = new WebSocketMessageResponse(false, "PLC数据服务未设置，无法控制设备");
                Log.e(TAG, "PLC数据服务未设置，无法控制设备");

            }
        } catch (Exception e) {
            String error = "处理单设备控制命令异常: " + e.getMessage();
            Log.e(TAG, error, e);
            messageResponse = new WebSocketMessageResponse(false, error);
        }

        if (callback != null) {
            messageResponse.setSender("kinggu");
            messageResponse.setReceiver(message.getSender());
            callback.sendMessage(gson.toJson(messageResponse));
        }
    }

}